package service;

import pojo.Exercises;
import pojo.Result;
import utils.CalculateUtil;
import utils.FileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author
 * @Date 2023/9/25
 */
public class GenerateServiceImpl implements GenerateService {

    @Override
    public void generateAnswer(Exercises e) {
        Queue<String> queue = new LinkedList<>();
        ArrayList<String> eValueList = e.getValueList();
        //将所有运算数进队列
        for (int i = 2 * e.getOperatorNumber(); i > e.getOperatorNumber() - 1; i--) {
            queue.add(eValueList.get(i));
        }
        //取出每个运算符,再从队列取出两个数字进行运算，结果再放入队尾中，直到取完所有运算符，此时队列中的数字为最终答案
        for (int i = e.getOperatorNumber() - 1; i >= 0; i--) {
            //取出运算符
            String opSymbol = eValueList.get(i);
            //从队列取出两个数字
            String num1 = queue.remove();
            String num2 = queue.remove();
            //计算两数运算后结果
            //getEnumByOpSymbol(opSymbol)得到运算符的计算方法并计算
            String answer = OperatorEnum.getEnumByOpSymbol(opSymbol).op(num1, num2);
            //计算过程出现不符合条件的数值，就返回null
            if (answer == null) {
                e.setAnswer(null);
                return;
            }
            queue.add(answer);
        }
        e.setAnswer(queue.remove());
    }

    @Override
    public Result checkAnswer(List<Exercises> exercises) throws IOException {
        Result result = new Result();
        for (Exercises e : exercises) {
            //获取每条题目的正确答案
            generateAnswer(e);
            if (e.getAnswer().equalsIgnoreCase(e.getStudentAnswer())) {
                result.getCorrectList().add(e.getNumber());
            } else {
                result.getWrongList().add(e.getNumber());
            }
        }
        //将结果输出到文件
        FileUtil.writeCheckResultToFile(result);
        return result;
    }

    @Override
    public List<Exercises> readFile(File exercisesFile, File answerFile) throws Exception {
        BufferedReader exercisesReader = FileUtil.getBufferedReader(exercisesFile);
        BufferedReader answerReader = FileUtil.getBufferedReader(answerFile);
        String question;
        List<Exercises> exercisesList = new LinkedList<>();
        while ((question = exercisesReader.readLine()) != null) {
            String answer = answerReader.readLine();
            System.out.printf("question=%s\n", question);
            System.out.printf("answer=%s\n", answer);
            //解析成Exercises对象
            Exercises exercises = CalculateUtil.parseExercises(question);
            //填入学生答案
            exercises.setStudentAnswer(CalculateUtil.parseAnswer(answer));
            exercisesList.add(exercises);
        }
        return exercisesList;
    }
}
